package com.vecspace.core.support.auth;

import java.lang.reflect.Method;


/**用于注册全局全局判断权限
 * 
 * @version: 1.0
 * @author: wanghua
 */
public class BaseAuthManager{
	private static IAuthManager authManager;///在LoginManager类的静态构造函数中对此变量进行赋值,authManager在BaseController中用到

	public static IAuthManager getAuthManager() {
		return BaseAuthManager.authManager;
	}

	public static void setAuthManager(IAuthManager authManager) {
		BaseAuthManager.authManager = authManager;
	}
	
	/**检查此method是否被授权访问，如果需要授权，但是没有进行授权，则抛出异常。
	 * 根据@Auth注解的权限参数进行判断
	 * @param method
	 * @return
	 * @throws Exception 
	 * @author: wanghua
	 */
	public static boolean checkAuthorization(Method method) throws Exception {
		int authTag = 0;
		IAuthManager authManager = BaseAuthManager.getAuthManager();
		if(authManager != null) {
			TAuth authCriteria = method.getAnnotation(TAuth.class);
			if(authCriteria != null){
				String funcIds = authCriteria.funcId();
				if(funcIds != null && funcIds.length()>0){
					String errMsg = "";
					if(authManager != null){
						boolean authed = false;
						String[] funcIdArr = funcIds.split(",");
						for(String funcId : funcIdArr){
							authTag = authManager.getAuthTag(funcId.trim());
	
							if(authCriteria.needAuthorized() && authTag <= 0) {
								errMsg = "40011:访问此功能需要授权，请联系管理员进行授权。功能编号："+funcIds;
							}else if(authCriteria.needEditAuth() && authTag != 2)  {
								errMsg = "40012:访问此功能需要授权为[读写]权限，请联系管理员进行授权。功能编号："+funcIds;
							}else{
								authed = true;
								break;
							}
						}
						if(!authed){
							throw new Exception(errMsg);
						}
					}
	
				}
			}
		}
		return true;
	}
}
